package foodmaterial.utils;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Component
public class RandomValidateCodeUtil {
    private int width = 105;
    private int height = 30;
    private int lineSize = 40;

    private static final Logger LOGGER = LoggerFactory.getLogger(RandomValidateCodeUtil.class);

    private Random random = new Random();

    private Font fixFont = new Font("FixedSys", Font.CENTER_BASELINE, 24);

    private Font romanFont = new Font("Times New Roman", Font.ROMAN_BASELINE, 24);
    private Font mirFont = new Font("Microsoft YaHei", Font.ROMAN_BASELINE, 24);

    private Color getRandColor(int fc, int bc) {
        if (fc > 255) fc = 255;
        if (bc > 255) bc = 255;
        int r = fc + random.nextInt(bc - fc - 16);
        int g = fc + random.nextInt(bc - fc - 14);
        int b = fc + random.nextInt(bc - fc - 18);
        return new Color(r, g, b);
    }

    public void getRandCode(HttpSession session, HttpServletResponse response) {
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);
        Graphics g = image.getGraphics();
        g.fillRect(0, 0, width, height);
        g.setFont(romanFont);
        g.setColor(getRandColor(110, 133));
        for (int i = 0; i <= lineSize; i++) {
            drawLine(g);
        }
        int opData1 = random.nextInt(10);
        int opData2 = random.nextInt(10) ;
        if (opData1 < opData2) {
            int temp = opData1 ;
            opData1 = opData2 ;
            opData2 = temp ;
        }
        int op = random.nextInt(2);
        int finalResult = op == 1 ? opData1 + opData2 : opData1 - opData2 ;
        drawString(g, opData1, op,1);
        drawString(g, opData2, op,2);

        g.dispose();
        try {
            ImageIO.write(image, "JPEG", response.getOutputStream());
            session.setAttribute("validateCode",Integer.toString(finalResult));
        } catch (Exception e) {
        	e.printStackTrace();
        }
    }

    private void drawString(Graphics g, int opData, int op,int i) {
        g.setFont(mirFont);
        g.setColor(new Color(random.nextInt(101), random.nextInt(111), random.nextInt(121)));
        String rand = opData + (i == 1 ? (op == 1 ? "加" : "减") : "=") ;
        g.translate(random.nextInt(3), random.nextInt(3));
        g.drawString(rand, 5 * i + (i - 1) * 45 , 24);
    }

    private void drawLine(Graphics g) {
        int x = random.nextInt(width);
        int y = random.nextInt(height);
        int xl = random.nextInt(13);
        int yl = random.nextInt(15);
        g.drawLine(x, y, x + xl, y + yl);
    }
}
